﻿using BW.Mes.WinForms.BasicData;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.LineForm1;

namespace BW.Mes.WinForms.BasicData
{
    public partial class LineForm1 : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _lineApiBaseUrl = "https://localhost:7274";
        public LineForm1()
        {
            InitializeComponent();
            //初始化httpClient
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 窗体加载时获取数据
            this.Load += LineForm1_Load;
            gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;
        }
        private async void LineForm1_Load(object sender, EventArgs e)
        {
            await LoadLineData();
        }
        private async Task LoadLineData()
        {
            try
            {

                var line = await GetApiDataAsync<List<LineModel>>("api/Line/GetLine");



                // 确保清除旧数据源并重新设置
                gridControl1.DataSource = null;
                gridControl1.DataSource = line;

                // 确保网格视图显示数据
                gridView1.PopulateColumns();
                gridView1.BestFitColumns();
                gridView1.RefreshData();

                AfterBindLineData();

            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
            }
        }
        /// <summary>
        /// 获取产线
        /// </summary>
        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_lineApiBaseUrl}/{endpoint}");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                // 调试显示原始响应内容
                Console.WriteLine($"API响应: {responseBody}");

                // 先解析为JObject以便提取内部数据
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

                // 假设数组数据在"data"字段中
                if (jsonObject["pageDatas"] != null)
                {
                    string dataJson = jsonObject["pageDatas"].ToString();
                    Console.WriteLine($"提取的pageDatas字段: {dataJson}");

                    return JsonConvert.DeserializeObject<T>(dataJson);
                }

                return JsonConvert.DeserializeObject<T>(responseBody);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
                return default;
            }
        }
        // 提交数据到API
        public async Task<bool> PostApiDataAsync<T>(string endpoint, T data)
        {
            try
            {
                string jsonData = JsonConvert.SerializeObject(data);
                HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.PostAsync($"{_lineApiBaseUrl}/{endpoint}", content);
                response.EnsureSuccessStatusCode();
                return true;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"提交数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        public class LineModel
        {
            public long Id { get; set; }
            /// <summary>
            /// 产线编号
            /// </summary>
            [DisplayName("产线编号")]
            public string LineCode { get; set; }
            /// <summary>
            /// 产线名称
            /// </summary>
            /// 
            [DisplayName("产线名称")]
            public string LineName { get; set; }

            /// <summary>
            /// 产线描述
            /// </summary>
            /// 
            [DisplayName("产线描述")]
            public string LineMsg { get; set; }
            [DisplayName("所属车间")]
            public string WorkshopName { get; set; }
            [DisplayName("创建人")]
            public string CreatedBy { get; set; }
            [DisplayName("创建时间")]
            public DateTime CreatedAt { get; set; } = DateTime.Now;
            [DisplayName("修改时间")]
            public DateTime? UpdatedAt { get; set; }
        }
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            LoadLineData();
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }


        private void simpleButton1_Click_1(object sender, EventArgs e)
        {
            var form = new AddLineForm();
            if (form.ShowDialog() == DialogResult.OK)
            {
                LoadLineData();
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadLineData();
        }

        private void EnsureSerialNumberColumn()
        {
            if (gridView1.Columns["序号"] == null)
            {
                var col = gridView1.Columns.AddField("序号");
                col.Caption = "序号";
                col.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
                col.Visible = true;
                col.VisibleIndex = 0;
            }
            else
            {
                gridView1.Columns["序号"].Visible = true;
                gridView1.Columns["序号"].VisibleIndex = 0;
            }
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.IsGetData)
            {
                e.Value = e.ListSourceRowIndex + 1;
            }
        }

        private void AfterBindLineData()
        {
            EnsureSerialNumberColumn();
            var idColumn = gridView1.Columns["Id"];
            if (idColumn != null) idColumn.Visible = false;
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            string code = textEditCode.Text.Trim();
            string name = textEditName.Text.Trim();
            if (string.IsNullOrEmpty(code) && string.IsNullOrEmpty(name))
            {
                // 重新加载全部数据
                LoadLineData();
                return;
            }
            var data = gridControl1.DataSource as IEnumerable<object>;
            if (data == null) return;
            var filtered = data.Where(item =>
            {
                var type = item.GetType();
                var codeProp = type.GetProperty("LineCode") ?? type.GetProperty("编号");
                var nameProp = type.GetProperty("LineName") ?? type.GetProperty("名称");
                string codeVal = codeProp?.GetValue(item)?.ToString() ?? "";
                string nameVal = nameProp?.GetValue(item)?.ToString() ?? "";
                return (string.IsNullOrEmpty(code) || codeVal.Contains(code)) &&
                       (string.IsNullOrEmpty(name) || nameVal.Contains(name));
            }).ToList();
            gridControl1.DataSource = filtered;
            EnsureSerialNumberColumn();
            var idColumn = gridView1.Columns["Id"];
            if (idColumn != null) idColumn.Visible = false;
        }
    }
}